package com.ccsoft.atools.controller;


import com.ccsoft.atools.utils.JsonResult;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;

@CrossOrigin
@RestController
@RequestMapping("/jasypt")
public class JasyptController {

    @GetMapping("/encrypt/{salt}/{data}")
    public JsonResult encrypt(@PathVariable String salt, @PathVariable String data) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword(salt);// 加密用到的盐
        return JsonResult.ok(textEncryptor.encrypt(data));
    }

    @GetMapping("/decrypt/{salt}/**")
    public JsonResult decrypt(@PathVariable String salt, HttpServletRequest request) {
        String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
        String path2 = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
        String args = new AntPathMatcher().extractPathWithinPattern(path2, path);

        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword(salt);// 加密用到的盐
        return JsonResult.ok(textEncryptor.decrypt(args));
    }

}